package cn.stylefeng.guns.modular.rest.xlbapi;


import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.service.*;
import cn.stylefeng.guns.modular.rest.xlbapi.vo.DeliToStoreIby;
import cn.stylefeng.guns.modular.rest.xlbapi.vo.SyncDepartOrderIby;
import cn.stylefeng.guns.modular.rest.xlbapi.vo.SyncDepartOrderListIby;
import cn.stylefeng.guns.modular.transport.entity.TDispatch;
import cn.stylefeng.guns.modular.transport.entity.TransportReceipt;
import cn.stylefeng.guns.modular.transport.service.TDispatchService;
import cn.stylefeng.guns.modular.transport.service.TransportReceiptService;
import cn.stylefeng.guns.modular.xlb.entity.XlbApiDeliToStore;
import cn.stylefeng.guns.modular.xlb.entity.XlbApiDepartOrder;
import cn.stylefeng.guns.modular.xlb.model.params.XlbApiDeliToStoreParam;
import cn.stylefeng.guns.modular.xlb.service.XlbApiDeliToStoreService;
import cn.stylefeng.guns.modular.xlb.service.XlbApiDepartOrderService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.*;

@Api(tags = "新零帮接口调用")
@Controller
@RequestMapping("/rest/xlbApi")
public class RestXlbApiController {


    @Autowired
    private XlbApiDeliToStoreService xlbApiDeliToStoreService;

    @Autowired
    private XlbApiDepartOrderService xlbApiDepartOrderService;

    @Autowired
    private BasicCustomerService basicCustomerService;

    @Autowired
    private TransportReceiptService transportReceiptService;

    @Autowired
    private TDispatchService tDispatchService;


    // 同步发车单信息
    @ApiOperation(value = "同步发车单信息", notes = "新零帮装车完成，发运的时候将发运成功的发车单信息通过该接口同步给极鹿系统")
    @ResponseBody
    @RequestMapping(value = "/syncDepartOrder", method = {RequestMethod.POST})
    public ResponseData syncDepartOrder(@RequestBody SyncDepartOrderIby syncDepartOrderIby) {
        if(ToolUtil.isEmpty(syncDepartOrderIby.getDepartOrderId())){
            return ResponseData.error("发车单号不能为空");
        }
        //判断是否重复调用
        Integer count = xlbApiDepartOrderService.lambdaQuery()
                .eq(XlbApiDepartOrder::getDepartOrderId,syncDepartOrderIby.getDepartOrderId())
                .count();
        if(count> 0){
            return ResponseData.success("["+syncDepartOrderIby.getDepartOrderId() + "]重复发车！");
        }

        BasicCustomer basicCustomer = null;
        if(ToolUtil.isEmpty(syncDepartOrderIby.getDeliStoreId())){
            return ResponseData.error("发货门店不能为空！");
        }else{
            basicCustomer = basicCustomerService.findListByStoreIdXlb(syncDepartOrderIby.getDeliStoreId());
            if(ToolUtil.isEmpty(basicCustomer)){
                return ResponseData.error("发货门店ID:"+syncDepartOrderIby.getDeliStoreId()+" 极鹿未配置，无法接收数据！");
            }
        }

        return xlbApiDepartOrderService.syncDepartOrder(syncDepartOrderIby, basicCustomer);
//        return ResponseData.success();
    }

    // 同步发车单信息
    @ApiOperation(value = "同步发车单信息", notes = "新零帮装车完成，发运的时候将发运成功的发车单信息通过该接口同步给极鹿系统")
    @ResponseBody
    @RequestMapping(value = "/syncDepartOrderList", method = {RequestMethod.POST})
    public ResponseData syncDepartOrderList(SyncDepartOrderListIby syncDepartOrderListIby) {
//        Map<String, Map<String, SyncDepartOrderIby>> departOrderMap = new HashMap<>();
//        // 承运商集合
//        Set<String> carrierNameSet = new HashSet<>();
//        // 线路集合
//        Set<String> lineNameSet = new HashSet<>();
//        // 门店集合
//        Set<String> receStoreNameSet = new HashSet<>();
//        //车辆集合
//        Set<String> carNumberSet = new HashSet<>();
//        //司机集合
//        Set<String> driverNameSet = new HashSet<>();
//
//        // 根据 发货门店id 查询客户信息，找到对应的 所属项目
//        String deliStoreId = null;
//        if (ToolUtil.isNotEmpty(syncDepartOrderListIby) && ToolUtil.isNotEmpty(syncDepartOrderListIby.getList())) {
//            Map<String, SyncDepartOrderIby> receStoreIdMap = null;
//            for (SyncDepartOrderIby obj : syncDepartOrderListIby.getList()) {
//                deliStoreId = obj.getDeliStoreId();
//                carrierNameSet.add(obj.getCarrierName());
//                carNumberSet.add(obj.getCarNumber());
//                driverNameSet.add(obj.getDriverName());
//
//                // MAP里面不存在，需要添加
//                if(ToolUtil.isEmpty(departOrderMap.get(obj.getDepartOrderId()))){
//                    receStoreIdMap = new HashMap<>();
//                    receStoreIdMap.put(obj.getReceStoreId(),obj);
//                    departOrderMap.put(obj.getDepartOrderId(),receStoreIdMap);
//                }else{
//                    // MAP里面不存在，需要新添加
//                    if(ToolUtil.isEmpty(departOrderMap.get(obj.getDepartOrderId()).get(obj.getReceStoreId()))){
//                        receStoreIdMap = new HashMap<>();
//                        receStoreIdMap.put(obj.getReceStoreId(),obj);
//                        departOrderMap.put(obj.getDepartOrderId(),receStoreIdMap);
//                    }else{
//                        SyncDepartOrderIby _syncDepartOrderIby = departOrderMap.get(obj.getDepartOrderId()).get(obj.getReceStoreId());
//                        // 行驶里程
//                        _syncDepartOrderIby.setMileage(_syncDepartOrderIby.getMileage().add(obj.getMileage()));
//                        // 商品数
//                        _syncDepartOrderIby.setGoodsCnt(_syncDepartOrderIby.getGoodsCnt() + obj.getGoodsCnt());
//                        // 商品件数
//                        _syncDepartOrderIby.setGoodsNum(_syncDepartOrderIby.getGoodsNum() + obj.getGoodsNum());
//                        // 商品封箱数
//                        _syncDepartOrderIby.setGoodsBoxNum(_syncDepartOrderIby.getGoodsBoxNum() + obj.getGoodsBoxNum());
//                        // 商品体积
//                        _syncDepartOrderIby.setGoodsVol(_syncDepartOrderIby.getGoodsVol().add(obj.getGoodsVol()));
//                        // 重新替换对象
//                        departOrderMap.get(obj.getDepartOrderId()).put(obj.getReceStoreId(),_syncDepartOrderIby);
//                    }
//                }
//                // 添加记录
//                XlbApiDepartOrderParam addObj = new XlbApiDepartOrderParam();
//                ToolUtil.copyProperties(obj, addObj);
//                addObj.setApiTm(new Date());
//                xlbApiDepartOrderService.add(addObj);
//            }
//            BasicCustomer basicCustomer = null;
//            if(ToolUtil.isNotEmpty(deliStoreId)){
//                basicCustomer = basicCustomerService.findListByStoreIdXlb(deliStoreId);
//            }
//
//            if(ToolUtil.isEmpty(basicCustomer)){
//                return ResponseData.error("发货门店不存在，无法接收数据");
//            }
//
//            // 判断承运商是否存在，不存在则新增
//            for(String str : carNumberSet){
//                BasicCarrierResult carrierObj = basicCarrierService.findByCarrierName(str, basicCustomer.getCustomerOperateId().longValue());
//                if(ToolUtil.isEmpty(carrierObj)){
//                    BasicCarrierParam addCarrierObj = new BasicCarrierParam();
//                    addCarrierObj.setOperateId(basicCustomer.getCustomerOperateId().longValue());
//                    addCarrierObj.setOperateName(basicCustomer.getCustomerOperateName());
//                    addCarrierObj.setDeliverId(1L);
//                    addCarrierObj.setDeptId(basicCustomer.getDeptId());
//                    addCarrierObj.setCarrierName(str);
//                    addCarrierObj.setCreateUser("新零帮接口");
//                    addCarrierObj.setCreateTime(new Date());
//                    basicCarrierService.add(addCarrierObj);
//                }
//            }
//
//            // 判断线路是否存在，不存在则新增
//            for(String str : lineNameSet){
//                BasicLineResult lineObj = basicLineService.findByName(str, basicCustomer.getCustomerOperateId().longValue());
//                if(ToolUtil.isEmpty(lineObj)){
//                    BasicLineParam addLineObj = new BasicLineParam();
//                    addLineObj.setOperateId(basicCustomer.getCustomerOperateId());
//                    addLineObj.setOperateName(basicCustomer.getCustomerOperateName());
//                    addLineObj.setDeliverId(1L);
//                    addLineObj.setDeptId(basicCustomer.getDeptId());
//                    addLineObj.setLineName(str);
//                    addLineObj.setCreateName("新零帮接口");
//                    addLineObj.setCreateTimes(DateUtil.getDateS());
//                    basicLineService.add(addLineObj);
//                }
//            }
//
//            // 判断门店是否存在，不存在则新增
//            for(String str : receStoreNameSet){
//                BasicPutgoodsResult putgoodsObj = basicPutgoodsService.findByName(str, basicCustomer.getId().longValue());
//                if(ToolUtil.isEmpty(putgoodsObj)){
//                    BasicPutgoodsParam addPutgoodsObj = new BasicPutgoodsParam();
//                    addPutgoodsObj.setPutgoodsCustomerId(basicCustomer.getId());
//                    addPutgoodsObj.setPutgoodsOperateName(basicCustomer.getCustomerName());
//                    addPutgoodsObj.setDeliverId(1L);
//                    addPutgoodsObj.setDeptId(basicCustomer.getDeptId());
//                    addPutgoodsObj.setPutgoodsName(str);
//                    addPutgoodsObj.setCreateUser(-1L);
//                    addPutgoodsObj.setCreateTime(new Date());
//                    basicPutgoodsService.add(addPutgoodsObj);
//                }
//            }
//            // 判断车辆是否存在，不存在则新增
//            for(String str : carNumberSet){
//                BasicPrivatecarResult basicPrivatecar = this.basicPrivatecarService.findByName(str, basicCustomer.getId().longValue());
//                if(ToolUtil.isEmpty(basicPrivatecar)){
//                    BasicPrivatecarParam addPrivatecarObj = new BasicPrivatecarParam();
//                    addPrivatecarObj.setOperateId(basicCustomer.getCustomerOperateId().longValue());
//                    addPrivatecarObj.setOperateName(basicCustomer.getCustomerOperateName());
//                    addPrivatecarObj.setDeliverId(1L);
//                    addPrivatecarObj.setDeptId(basicCustomer.getDeptId());
//                    addPrivatecarObj.setPrivatecarCarnumber(str);
//                    addPrivatecarObj.setCreateUser(-1L);
//                    addPrivatecarObj.setCreateTime(new Date());
//                    this.basicPrivatecarService.add(addPrivatecarObj);
//                }
//            }
//            // 判断司机是否存在，不存在则新增
//            for(String str : driverNameSet){
//                BasicDriverResult basicDriver = basicDriverService.findByName(str, basicCustomer.getId().longValue());
//                if(ToolUtil.isEmpty(basicDriver)){
//                    BasicDriverParam addDriverObj = new BasicDriverParam();
//                    addDriverObj.setDriverOperateId(basicCustomer.getCustomerOperateId());
//                    addDriverObj.setDriverOperateName(basicCustomer.getCustomerOperateName());
//                    addDriverObj.setDeliverId(1L);
//                    addDriverObj.setDeptId(basicCustomer.getDeptId());
//                    addDriverObj.setDriverName(str);
//                    addDriverObj.setCreateUser(-1L);
//                    addDriverObj.setCreateTime(new Date());
//                    basicDriverService.add(addDriverObj);
//                }
//            }
            // 生成对应的货运订单

            // 生成对应的货运订单明细

            // 生成对应的运输单

            // 生成对应的运输单明细

            // 生成对应的回单表

//        }
        return ResponseData.success();
    }

    // 同步门店送达信息
    @Transactional(rollbackFor = Exception.class,timeout = 1800)
    @ApiOperation(value = "同步门店送达信息", notes = "司机送达完成后，调用该接口同步发车单送达状态，根据门店完成的送达数量自动判断发车单是否全部完成")
    @ResponseBody
    @RequestMapping(value = "/deliToStore", method = {RequestMethod.POST})
    public ResponseData deliToStore(@RequestBody DeliToStoreIby deliToStoreIby) {
        if(ToolUtil.isEmpty(deliToStoreIby.getDepartOrderId())){
            return ResponseData.error("发车单号不能为空");
        }
        //判断是否重复调用
        Integer count = xlbApiDeliToStoreService.lambdaQuery()
                .eq(XlbApiDeliToStore::getDepartOrderId,deliToStoreIby.getDepartOrderId())
                .count();
        if(count> 0){
            return ResponseData.success("["+deliToStoreIby.getDepartOrderId() + "]重复送达！");
        }
        Integer count1 = tDispatchService.lambdaQuery()
                .eq(TDispatch::getDispatchNumber, deliToStoreIby.getDepartOrderId())
                .count();
        if(count1 < 1){
            return ResponseData.success("发车单号不存在");
        }
        // 批量修改送达状态
        transportReceiptService.lambdaUpdate()
                .eq(TransportReceipt::getDispatchNumber,deliToStoreIby.getDepartOrderId())
                .set(TransportReceipt::getSdtstate,"已送达")
                .set(TransportReceipt::getSdtime,deliToStoreIby.getDeliverTm())
                .set(TransportReceipt::getSdusername,deliToStoreIby.getDeliverName())
                .update();

        // 批量修改送达状态
        tDispatchService.lambdaUpdate()
                .eq(TDispatch::getDispatchNumber,deliToStoreIby.getDepartOrderId())
                .ne(TDispatch::getTstate,"待定价")
                .set(TDispatch::getTstate,"已完成")
                .set(TDispatch::getReturnTstate,"已回单")
                .update();

        //添加调用记录
        XlbApiDeliToStoreParam addObj = new XlbApiDeliToStoreParam();
        ToolUtil.copyProperties(deliToStoreIby, addObj);
        addObj.setApiTm(new Date());
        xlbApiDeliToStoreService.add(addObj);

        return ResponseData.success();
    }
}
